﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using Budgeter.Properties;

namespace Budgeter
{
    public static class Receipt
    {

        internal const string FORMAT = "000-000";
        internal const string FORMAT_ARG = "{0:000-000}";
        internal const int DEFAULT_RECEIPT_NUMBER_MAX = 1000000;

        internal static int GenerateUniqueReceiptNumber(Models.BudgeterContext db)
        {
            int max = Settings.Default.ReceiptNumberMax;
            if (max <= DEFAULT_RECEIPT_NUMBER_MAX)
                max = DEFAULT_RECEIPT_NUMBER_MAX;

            int n;
            do
            {
                n = new Random().Next() % max;
            } while (db.Budgets.Any(x => x.ReceiptNumber == n));
            return n;
        }

        /// <summary>
        /// Formats a receipt number using the standard formatting for display.
        /// </summary>
        /// <param name="n">The receipt number to format.</param>
        /// <returns>The formatted string, ready for display.</returns>
        public static string FormatReceiptNumber(int n)
        {
            return n.ToString(FORMAT);
        }

        /// <summary>
        /// Parses a Receipt Number by stripping out any non-numeric 
        /// characters and then parsing as an int.
        /// </summary>
        /// <param name="receiptNumber">The ReceiptNumber string to parse.</param>
        /// <returns>The parsed receipt number.</returns>
        public static int ParseReceiptNumber(string receiptNumber)
        {
            var filtered = new string(receiptNumber.Where(c => c >= '0' && c <= '9').ToArray());
            return int.Parse(filtered);
        }

    }
}